package com.think.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.think.entity.Station;
import com.think.mapper.StationMapper;
import com.think.util.DistanceUtils;
import com.think.vo.StationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class CalculationService {

    @Autowired
    private StationMapper stationMapper;

    /**
     * 获取该经纬度到所有站点的距离集合
     * @return
     */
    public TreeMap<Station,Double> getStationMap(Double lat, Double lgt){
        TreeMap<Station,Double> map = new TreeMap<Station, Double>(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                //如果有空值，直接返回0
                if (o1 == null || o2 == null) {
                    return 0;
                }
                return String.valueOf(o1).compareTo(String.valueOf(o2));
            }
        });
        QueryWrapper<Station> wrapper = new QueryWrapper<>();
        List<Station> stationList = stationMapper.selectList(wrapper);
        //查到数据库里面的所有站点list,循环list计算该经纬度到每个站点的距离
        stationList.forEach(station -> {
            double distance = DistanceUtils.getDistance(lat, lgt, station.getLat(), station.getLgt());
            map.put(station, distance);
        });
        return map;
    }

    /**
     * 根据输入的经纬度计算到所有站点的距离，返回最大、最小和中位值。
     * @param lat
     * @param lgt
     */
    public List<StationVO> getList(Double lat, Double lgt){
        TreeMap<Station, Double> stationDoubleTreeMap = getStationMap(lat, lgt);
        List<StationVO> list = new ArrayList<>();
        for (Map.Entry<Station, Double> entry : stationDoubleTreeMap.entrySet()) {
            list.add(StationVO.builder().id(entry.getKey().getId()).stationName(entry.getKey().getStationName())
                            .lat(entry.getKey().getLat()).lgt(entry.getKey().getLgt()).location(entry.getValue())
                    .build());
        }
        List<StationVO> result = new ArrayList<>();
        int size = list.size();
        result.add(list.get(0));
        result.add(list.get(size - 1));
        return result;
    }
}
